# -*- coding: utf-8 -*-
import py_global
import json
import logging
from datetime import datetime, date

# pip install redis
from redis import Redis, StrictRedis, ConnectionPool

logger = logging.getLogger(__name__)

# 连接池
connection_pool = ConnectionPool(
    host='127.0.0.1',
    port=6379,
    word='',
    db=5,
    max_connections=5
)


def redis_cache(redis_client: Redis):
    """redis缓存"""

    datetime_format = '%Y-%m-%d %H:%M:%S'
    date_format = '%Y-%m-%d'

    kwargs = {
        'arg0': 'string',
        'arg1': date.today().strftime(date_format)
    }
    dict_data = {
        'start_time': datetime.now().strftime(datetime_format),
        'task_status': 0,
    }
    dict_data.update(kwargs)
    redis_client.setnx('dict_data', json.dumps(dict_data))

    result = redis_client.get('dict_data')
    if isinstance(result, bytes):
        result = result.decode()

    dict_data = json.loads(result)
    logger.info(dict_data)

    pass


def redis_string(redis_client: Redis):
    name = 'key-name'
    value = 'redis-value'
    # set操作返回bool类型
    result = redis_client.setex(name, 30, value)
    # get有值返回bytes类型，
    result = redis_client.get(name)
    if result:  # get没有返回None
        logger.info(f'result:{result.decode()}')
        pass

    result = redis_client.exists(name)

    expire = redis_client.ttl(name)
    logger.info(f'expire:{expire}')

    pass


def redis_list(redis_client: Redis):
    redis_list_key = 'redis_list_key'
    redis_client.expire(redis_list_key, 30)
    redis_client.lpush(redis_list_key, '123')
    redis_client.lpush(redis_list_key, '456')

    pass


def redis_hash(redis_client: Redis):
    redis_hash_key = 'redis_hash_key'
    # redis_client.expire(redis_hash_key, 30)
    redis_client.hset(redis_hash_key, 'k0', 'v0')
    redis_client.hset(redis_hash_key, 'k1', 'v1.1')
    mapping_dict = {
        'k1': 'v1.2',
        'k2': 'v2.2',
        'k3': 'v3.2',
    }
    redis_client.hset(redis_hash_key, mapping=mapping_dict)
    pass


def transaction_pipeline(redis_client):
    key = 'sum'
    redis_client.set(key, 1)
    pipeline = redis_client.pipeline(transaction=True)
    pipeline.multi()
    pipeline.incr(key)
    pipeline.incr(key)
    values = pipeline.execute()
    logger.info(values)

    pass


def test_redis_client():
    redis_client: Redis = StrictRedis(
        host='127.0.0.1',
        port=6379,
        password='chench',
        # decode_responses=True
    )
    # redis_client = Redis(connection_pool=connection_pool)
    # redis_cache(redis_client)
    # redis_string(redis_client)
    # redis_list(redis_client)
    redis_hash(redis_client)
    redis_client.close()


if __name__ == '__main__':
    test_redis_client()
